package com.ybwh.springboot1.common;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.ybwh.springboot1.model.po.User;
import com.ybwh.springboot1.service.UserService;
import com.ybwh.springboot1.util.TokenUtil;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * controller方法参数解析器
 * </p>
 *
 * @author ybwh
 * @since 2019年5月17日 下午2:30:09
 */
@Slf4j
@AllArgsConstructor
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

	private UserService userService;

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		if (UserInfo.class.equals(parameter.getParameterType())) {
			return true;
		}
		return false;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		HttpServletRequest request= (HttpServletRequest) webRequest.getNativeRequest();
		String token = TokenUtil.getToken(request);
		if(StringUtils.isBlank(token)) {
			log.error("can not get token for  UserInfoArgumentResolver！");
			return null;
		}
		
		TokenInfo tokenInfo = TokenUtil.decodeToken(token);
		
		User user = userService.queryUserByUsername(tokenInfo.getUsername());
		if(null == user) {
			log.error("can not find user for  {}",tokenInfo.getUsername());
			return null;
		}
		
		UserInfo userInfo = new UserInfo();
		BeanUtils.copyProperties(user, userInfo);
		
		return userInfo;
	}

}
